package com.SFA.DownLoadPhoto;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


import android.content.Context;
import android.database.sqlite.SQLiteCursor;

import com.FrameWork.DB.DataProvider;
import com.FrameWork.Utils.Utils;
import com.SFA.R;

public class DownloadPhotoUtils {

	/**
	 * 传入一个list<ProductPhotoEntity>
	 * 根据ProductPhotoEntity.getId和File一对一对照
	 * 如果存在则remove掉
	 */
	public static List<ProductPhotoEntity> notExistPhotoInfo(List<ProductPhotoEntity> ppeList){
		List<ProductPhotoEntity> resList = new ArrayList<ProductPhotoEntity>();
		if(ppeList==null || ppeList.size()<=0)
			return resList;
		
		for(int i=0; i<ppeList.size(); i++){
			
			File fileName = new File(Utils.BuildFilePath("/"+Utils.ImageFolder +"/" +  ppeList.get(i).getPhotoName()));
			if(!fileName.exists())
			{
				resList.add(ppeList.get(i));
			}
		}

		return resList;
	}

	/**
	 * 查询所有Photo的信息
	 */
	public static List<ProductPhotoEntity> allPhotoInfo(Context context){

		if(context == null)
			return null;
		SQLiteCursor cursor = null;
		List<ProductPhotoEntity> list = new ArrayList<ProductPhotoEntity>();;
		try {
			cursor = DataProvider.Instance(context).Query(context.getString(R.string.sql_DownloadPhotoList));
			while(cursor.moveToNext()){
				ProductPhotoEntity ppe = new ProductPhotoEntity();
				ppe.setId(cursor.getInt(cursor.getColumnIndex("ID")));
				ppe.setProductId(cursor.getInt(cursor.getColumnIndex("PRODUCT_ID")));
				System.out.println(ppe.getProductId());
				ppe.setPhotoName(cursor.getString(cursor.getColumnIndex("PHOTO_ID")));
				list.add(ppe);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
				cursor = null;
			}
		}
		return list;
	}

	/**
	 * 下载图片
	 * 返回一个保存的路径
	 */
	public static String downloadBitmap(Context context, String filePath, String file_name){
		InputStream inStream = null;
		String res = "";
		try {
			URL url = new URL(context.getString(R.string.WebServiceURL) + context.getString(R.string.WebService_DownloadPhoto) + filePath);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			inStream = conn.getInputStream();
			if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
				res = Utils.savFilepToSd(inStream, file_name);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			
			try {
				if(inStream != null)
				{
					inStream.close();
					inStream = null;
				}
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}

		}
		return res;
	}

















}
